﻿using System;
using System.Collections.ObjectModel;

using NUnit.Framework;

using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

namespace mvcForum.Tests.WebUI {

	[TestFixture]
	public class D001_ModeratorTests {
		private static IWebDriver driver;

		#region Initialization and cleanup
		[TestFixtureSetUp]
		public static void TestInitialize() {
			driver = TestHelper.GetDriver();
		}

		[TestFixtureTearDown]
		public static void TestCleanup() {
			if (driver != null) {
				driver.Close();
			}
		}

		[Test]
		public void GiveModeratorAccess() {
			driver.CreateUser(Constants.Users.Moderator.Username, Constants.Users.Moderator.Password, Constants.Users.Moderator.Email);
			driver.LogOff();

			driver.LogOn(Constants.Users.Admin.Email, Constants.Users.Admin.Password);

			driver.VisitURL("forumadmin/user", "users");

			Boolean found = false;
			ReadOnlyCollection<IWebElement> rows = driver.FindElement(By.Id("userlist")).FindElements(By.XPath("table/tbody/tr"));
			foreach (IWebElement row in rows) {
				if (row.FindElements(By.TagName("td"))[0].Text == Constants.Users.Moderator.Username) {
					found = true;
					row.FindElement(By.LinkText("Edit")).Click();
					break;
				}
			}

			if (!found) {
				//TODO:
				throw new ApplicationException("User not found!");
			}

			driver.Wait(2);

			driver.FindElement(By.LinkText("Add Group")).Click();

			WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
			wait.Until(drv => drv.FindElement(By.Id("newgroup")));

			driver.SelectOption("groupname", "Moderator");

			driver.FindElement(By.LinkText("Create")).Click();

			wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
			wait.Until(drv => drv.FindElement(By.Id("DeleteModerator")));
		}
		#endregion
	}
}